package com.volunteer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.volunteer.entity.*;
import com.volunteer.mapper.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 统计服务
 */
@Service
@RequiredArgsConstructor
public class StatisticsService {

    private final UserMapper userMapper;
    private final ActivityMapper activityMapper;
    private final PointRecordMapper pointRecordMapper;
    private final ActivityEnrollmentMapper enrollmentMapper;
    private final VolunteerProfileMapper volunteerProfileMapper;
    private final DemandApplicationMapper demandApplicationMapper;
    private final ServiceDemandMapper demandMapper;

    /**
     * 获取系统概览统计
     */
    public Map<String, Object> getOverviewStatistics() {
        Map<String, Object> result = new HashMap<>();

        // 志愿者总数
        LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
        userQuery.eq(User::getRole, "VOLUNTEER");
        long volunteerCount = userMapper.selectCount(userQuery);

        // 活动总数
        long activityCount = activityMapper.selectCount(null);

        // 进行中的活动
        LambdaQueryWrapper<Activity> activityQuery = new LambdaQueryWrapper<>();
        activityQuery.in(Activity::getStatus, "RECRUITING", "IN_PROGRESS");
        long ongoingActivityCount = activityMapper.selectCount(activityQuery);

        // 累计积分
        Integer totalPoints = pointRecordMapper.selectList(null).stream()
                .mapToInt(PointRecord::getPoints)
                .sum();

        // 近7日新增志愿者
        LambdaQueryWrapper<User> recentUserQuery = new LambdaQueryWrapper<>();
        recentUserQuery.eq(User::getRole, "VOLUNTEER")
                .ge(User::getCreateTime, LocalDateTime.now().minusDays(7));
        long recentVolunteerCount = userMapper.selectCount(recentUserQuery);

        // 近7日新增活动
        LambdaQueryWrapper<Activity> recentActivityQuery = new LambdaQueryWrapper<>();
        recentActivityQuery.ge(Activity::getCreateTime, LocalDateTime.now().minusDays(7));
        long recentActivityCount = activityMapper.selectCount(recentActivityQuery);

        result.put("volunteerCount", volunteerCount);
        result.put("activityCount", activityCount);
        result.put("ongoingActivityCount", ongoingActivityCount);
        result.put("totalPoints", totalPoints);
        result.put("recentVolunteerCount", recentVolunteerCount);
        result.put("recentActivityCount", recentActivityCount);

        return result;
    }

    /**
     * 获取用户个人统计数据
     */
    public Map<String, Object> getUserStatistics(Long userId) {
        Map<String, Object> result = new HashMap<>();

        // 从志愿者信息表获取累计时长和积分
        LambdaQueryWrapper<VolunteerProfile> profileQuery = new LambdaQueryWrapper<>();
        profileQuery.eq(VolunteerProfile::getUserId, userId);
        VolunteerProfile profile = volunteerProfileMapper.selectOne(profileQuery);
        
        BigDecimal totalHours = BigDecimal.ZERO;
        int totalPoints = 0;
        
        if (profile != null) {
            totalHours = profile.getTotalHours() != null ? profile.getTotalHours() : BigDecimal.ZERO;
            totalPoints = profile.getTotalPoints() != null ? profile.getTotalPoints() : 0;
        }

        // 参与活动数（已通过和已完成的报名）
        LambdaQueryWrapper<ActivityEnrollment> enrollmentQuery = new LambdaQueryWrapper<>();
        enrollmentQuery.eq(ActivityEnrollment::getUserId, userId)
                .in(ActivityEnrollment::getStatus, "APPROVED", "COMPLETED");
        long participatedActivities = enrollmentMapper.selectCount(enrollmentQuery);

        // 完成需求数
        LambdaQueryWrapper<ServiceDemand> demandQuery = new LambdaQueryWrapper<>();
        demandQuery.eq(ServiceDemand::getAssigneeId, userId)
                .eq(ServiceDemand::getStatus, "COMPLETED");
        long completedDemands = demandMapper.selectCount(demandQuery);

        result.put("totalHours", totalHours.doubleValue());
        result.put("totalPoints", totalPoints);
        result.put("participatedActivities", participatedActivities);
        result.put("completedDemands", completedDemands);

        return result;
    }
}

